<script setup lang="ts">
import { reactive, ref } from "vue";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import request from "@/utils/request.ts";
const formRef = ref()
const data = reactive({
  form: {
    username: '',
    password: '',
    role: '0',
  },
  rules: {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 1,max:4, message: '长度4位', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6,max:6, message: '密码6位', trigger: 'blur' },
    ],
  }
})

const login = () => {
  formRef.value.validate((valid:boolean) => {
    if (valid) {
      request.post("/loginUser",data.form).then(res => {
        if (res.status == 200) {//在request.ts中将response.data封装给了res
          localStorage.setItem("code_user",JSON.stringify(res.data || {}));
          //登录成功跳转到首页
          ElMessage.success("登陆成功")
          if(res.data.role === '1'||res.data.role === 1){
            router.push("/admin")
          }else {
            router.push("/");
          }
        }else{
          ElMessage.error("用户不存在或密码错误");
        }
      })
    }
  })
}
</script>
<template>
  <div class="bg">
    <div style="width: 350px; background-color: #fff; border-radius: 5px; box-shadow: 0 0 10px rgba(0,0,0,0.1); padding: 40px 20px">
      <el-form ref="formRef" :model="data.form" :rules="data.rules">
        <div style="margin-bottom: 40px; text-align: center; font-weight: bold; font-size: 24px">欢 迎 来 到 储 物 柜</div>
        <el-form-item prop="username">
          <el-input size="large" v-model="data.form.username" autocomplete="off" prefix-icon="User" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item prop="password">
          <el-input size="large" show-password v-model="data.form.password" autocomplete="off" prefix-icon="Lock" placeholder="请输入密码" />
        </el-form-item>

        <el-form-item prop="role">
          <el-select size="large" style="width: 100%" v-model="data.form.role">
            <el-option label="普通用户" value="0"></el-option>
            <el-option label="管理员" value="1"></el-option>
          </el-select>
        </el-form-item>
        <div style="margin-bottom: 20px">
          <el-button style="width: 100%" size="large" type="primary" @click="login">登 录</el-button>
        </div>
        <div style="text-align: right">
          还没有账号？请 <a style="color: #274afa" href="/register">注册</a>
        </div>
      </el-form>
    </div>
  </div>
</template>
<style scoped>
.bg {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background: url("../assets/images/bg_lg.jpg");
  background-size: cover;
}
</style>